package com.app.island.cash.requestview

import android.content.Intent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.app.island.cash.acts.EnterForgetPwdAct
import com.app.island.cash.acts.TabActivity
import com.app.island.cash.databinding.EnterPhoneActBinding
import com.app.island.cash.data.sigle.UserLoginCall
import com.app.island.cash.data.sigle.UidTokenRec
import com.app.island.cash.requestwork.AppService
import com.app.island.cash.requestwork.HttpResult
import com.app.island.cash.requestwork.NetClient
import com.app.island.cash.requestwork.RequestCallBack
import com.app.island.cash.utilstools.NetWorkLoadingUtil
import com.app.island.cash.utilstools.SystemUtils
import com.app.island.cash.utilstools.ToastUtil
import com.app.island.cash.utilstools.UserInfoManager

class EnterPhoneRequest {
    private var context:AppCompatActivity
    private var binding:EnterPhoneActBinding
    private var phone:String
    constructor(context:AppCompatActivity,binding: EnterPhoneActBinding,phone:String){
        this.context = context
        this.binding = binding
        this.phone = phone
        setClick()
    }

    private fun setClick() {
        binding.tvForgetPassword.setOnClickListener(View.OnClickListener {
            val intent = Intent(
                context,
                EnterForgetPwdAct::class.java
            )
            intent.putExtra("phone", binding.edPhoneNumber.text.toString().trim())
            context.startActivity(intent)
        })

        binding.tvLogin.setOnClickListener{ toLogin() }
    }

    private fun toLogin() {
        val password: String = binding.edPassword.text.toString().trim()
        if (password.length < 6 || password.length > 16) {
            ToastUtil.toast("Password length is 6~16")
            return
        }
        NetWorkLoadingUtil.showDialog(context)
        val userLoginCall = UserLoginCall(
            phone,
            SystemUtils.md5(password),
            SystemUtils.getIMEI(context),
            SystemUtils.macAddress()
        )
        val login = NetClient.getService(
            AppService::class.java
        ).login(userLoginCall)
        login.enqueue(object : RequestCallBack<HttpResult<UidTokenRec>?>() {
            override fun onSuccess(body: HttpResult<UidTokenRec>?) {
                UserInfoManager.instance.setPhoneNumber(phone)
                UserInfoManager.instance.token = body?.data?.token!!
                UserInfoManager.instance.uid = body?.data?.userId!!
                context.startActivity(Intent(context, TabActivity::class.java))
                context.finish()
            }
        })
    }
}